package com.me.modules.sys.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.common.base.CommonResult;
import com.me.modules.activiti.service.ActModelerService;
import com.me.modules.common.annotation.DataAuth;
import com.me.modules.common.annotation.SysLog;
import com.me.modules.common.common.Constant;
import com.me.modules.common.controller.BaseController;
import com.me.modules.common.page.PageHelper;
import com.me.modules.common.utils.PageUtils;
import com.me.modules.common.utils.Query;
import com.me.modules.common.utils.Result;
import com.me.modules.common.utils.ShiroUtils;
import com.me.modules.sys.entity.UserEntity;
import com.me.modules.sys.mapper.UserMapper;
import com.me.modules.sys.request.UserLoadPageRequest;
import com.me.modules.sys.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 *
 * @author me
 * @email me@163.com
 * @Date 2018-05-03 09:41:38
 */
@RestController
@RequestMapping("sys/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private ActModelerService actModelerService;
    @Autowired
    private GroupService groupService;
    @Autowired
    private GroupUserService groupUserService;
    @Autowired
    private UserMapper userMapper;

    /**
     * total是0  因为有个分页插件导致{@link PageHelper}
     */
    //	@SysLog("查看系统用户列表")
    @PostMapping("/loadPage")
    public CommonResult<Page<UserEntity>> loadPage(@RequestBody UserLoadPageRequest request) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        Page<UserEntity> page = userService.page(request.page(), queryWrapper);
        return CommonResult.success(page);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:user:list")
    @SysLog("查看系统用户列表")
    @DataAuth(tableAlias = "s")
    public Result list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<UserEntity> userList = userService.queryList(query);
        int total = userService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());
        Result result = Result.ok().put("page", pageUtil);

        return result;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:user:info")
    @SysLog("查看系统用户信息")
    public Result info(@PathVariable("id") Integer id) {
        UserEntity user = userService.queryObject(id);
        if (user != null) {
            user.setPassWord("");
            user.setRoleIdList(userRoleService.queryRoleIdList(user.getId()));
            user.setGroupIdList(groupUserService.queryGroupIdListByUserId(user.getId()));
        }
        return Result.ok().put("user", user);
    }

    /**
     * 主页用户信息
     */
    @RequestMapping("/info")
    public Result info() {
        UserEntity user = userService.queryObject(ShiroUtils.getUserId());
        //待办条数
        int myUpcomingCount = actModelerService.myUpcomingCount();
        //我的通知条数
        int myNoticeCount = noticeService.MyNoticeCount();
        return Result.ok().put("user", user).put("myUpcomingCount", myUpcomingCount).put("myNoticeCount", myNoticeCount);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:user:update")
    @SysLog("新增系统用户")
    public Result save(@RequestBody UserEntity user) {
        Result result = Result.ok();
        try {
            UserEntity addUser = userService.queryByLoginName(user.getLoginName());
            if (addUser == null) {
                userService.save(user);
            } else {
                result = Result.error("新增用户登录账户不能重复!!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("新增用户失败!!!请联系系统管理员");
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @RequiresPermissions("sys:user:update")
    @SysLog("修改系统用户")
    public Result update(@RequestBody UserEntity user) {
        Result result = Result.ok();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("loginName", user.getLoginName());
            List<UserEntity> checkList = userService.checkUserLoginName(map);
            if (checkList != null && checkList.size() > 0) {
                result = Result.error("新增用户登录账户不能重复!!!");
            } else {
                user.setPassWord(null);
                userService.update(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("修改用户失败!!!请联系系统管理员");
        }
        return result;
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @SysLog("用户修改密码")
    public Result updatePassword(UserEntity user) {
        int i = userService.updatePassword(user);
        if (i < 1) {
            return Result.error("更改密码失败");
        }
        return Result.ok("更改密码成功");
    }

    /**
     * 禁用、1
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    @SysLog("禁用系统用户")
    public Result delete(@RequestBody String[] ids) {
        userService.updateBatchStatus(ids, Constant.DELETE_STATUS.NO.getValue());
        return Result.ok();
    }

    /**
     * 启用、0
     */
    @RequestMapping("/enabled")
    @RequiresPermissions("sys:user:enabled")
    @SysLog("启用系统用户")
    public Result enabled(@RequestBody String[] ids) {
        userService.updateBatchStatus(ids, Constant.DELETE_STATUS.YES.getValue());
        return Result.ok();
    }

    /**
     * 重置密码
     */
    @RequestMapping("/reset")
    @RequiresPermissions("sys:user:reset")
    @SysLog("重置密码")
    public Result reset(@RequestBody String[] ids) {
        userService.resetPassWord(ids);
        return Result.ok("重置密码成功,密码为:" + Constant.DEF_PASSWORD);
    }

    /**
     * 查询工作组内的所有用户
     */
    @RequestMapping("/groupUser")
    @SysLog("查询组内用户")
    public Result groupUser(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
//		List<UserEntity> userList = userService.queryUserListByGroupId((Integer) params.get("id"));
        List<UserEntity> userList = userService.queryUserListByGroupId(query);
        int total = userService.queryUserTotalByGroupId(query);
        PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());
        return Result.ok().put("page", pageUtil);
    }


}
